<template>
    <div v-loading="loading">
        <ErrorBoundary>
            <ProTable 
            ref="proTable" 
            :columns="columns" 
            :request-api="getTableList" 
            :data-callback="dataCallback"
            row-key="id" 
            :tool-button="false"
            >
                <!-- 表格内容 -->
                 <!-- 标题 -->
      <template #etitle="scope">
        <el-link type="primary" @click="seeDetails(scope.row)">{{ formatTitle(scope.row) }}</el-link>
      </template>
            </ProTable>
        </ErrorBoundary>

        <ErrorBoundary>
            <EventDetailsMask ref="eventDetailsMask"></EventDetailsMask>
        </ErrorBoundary>
        <ErrorBoundary>
            <ChangeDetailsMask ref="changeDetailsMask"></ChangeDetailsMask>
        </ErrorBoundary>
        <ErrorBoundary>
            <ProblemDetailsMask ref="problemDetailsMask"></ProblemDetailsMask>
        </ErrorBoundary>
    </div>
</template>

<script setup lang="ts" name="PagePersonalTasksBox">
import { ref, reactive, nextTick ,onMounted,onBeforeUnmount,onErrorCaptured,h} from "vue";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance } from "@/components/ProTable/interface";
import { findPagePersonalTasks } from "@/api/modules/eventManagement";
import { useUserStore } from "@/stores/modules/user";
import EventDetailsMask from "@/components/Event/DetailsMask.vue";
import ChangeDetailsMask from "@/components/Change/DetailsMask.vue";
import ProblemDetailsMask from "@/components/Problem/DetailsMask.vue";
// ErrorBoundary 组件
const ErrorBoundary = {
    setup(props, { slots }) {
        const hasError = ref(false);

        onErrorCaptured((err) => {
            hasError.value = true;
            console.error('Component error:', err);
            return false;
        });

        return () => hasError.value
            ? h('div', { class: 'error-fallback' }, 'Component failed to load')
            : slots.default?.();
    }
};
const userStore = useUserStore();
// 表格配置项
const columns = reactive([
  { prop: "etitle", label: "标题" },
  { prop: "activityName", label: "任务名称" },
  { prop: "createTime", label: "创建时间" },
  { prop: "type", label: "任务类型", width: 120 }
]);

// ProTable 实例
const proTable = ref<ProTableInstance>();

const loading = ref(false);

// 如果你想在请求之前对当前请求参数做一些操作
const getTableList = (params: any) => {
  loading.value = true;
  return findPagePersonalTasks({
    assignee: userStore.username,
    _search: false,
    sidx: "eno",
    sord: "asc",
    page: params.pageNum,
    rows: params.pageSize
  }).catch(() => {
    loading.value = false;
  });
};

// dataCallback 是对于返回的表格数据做处理
const dataCallback = (data: any) => {
  loading.value = false;
  let list = data.data;
  console.log(list)
  list.forEach(element => {
    if (element.executionId.indexOf("request") >= 0) {
      element.type = "请求";
    } else if (element.executionId.indexOf("change") >= 0) {
      element.type = "变更";
    } else if (element.executionId.indexOf("problem") >= 0) {
      element.type = "问题";
    } else if (element.executionId.indexOf("release") >= 0) {
      element.type = "发布";
    }
  });
  return {
    list: list,
    total: data.totalSize,
    pageNum: data.page,
    pageSize: data.rows
  };
};

const formatTitle = item => {
  let txt = "";
  if (item.variables && item.variables.etitle) {
    txt = item.variables.etitle;
  }
  return txt;
};
const eventDetailsMask = ref<InstanceType<typeof eventDetailsMask> | null>();
const changeDetailsMask = ref<InstanceType<typeof changeDetailsMask> | null>();
const problemDetailsMask = ref<InstanceType<typeof problemDetailsMask> | null>();
onBeforeUnmount(() => {
    // 清理所有引用
    eventDetailsMask.value = null;
    changeDetailsMask.value = null;
    problemDetailsMask.value = null;
});
// 使用更健壮的引用管理
const detailsRefs = {
    request: eventDetailsMask,
    change: changeDetailsMask,
    problem: problemDetailsMask
};

const safeOpenDetails = (type: 'request' | 'change' | 'problem', variables: any) => {
    const ref = detailsRefs[type];
    if (ref?.value?.$el?.parentNode) {
        ref.value.open(variables);
    } else {
        console.warn(`${type} details component not available`);
        // 可选：延迟重试或显示错误信息
        setTimeout(() => {
            if (ref?.value?.$el?.parentNode) {
                ref.value.open(variables);
            }
        }, 100);
    }
};

const seeDetails = (item: any) => {
    if (!item.variables || (!item.variables.eno && !item.variables.dto)) {
        return;
    }

    nextTick(() => {
        if (item.executionId.includes("request")) {
            safeOpenDetails('request', item.variables);
        } else if (item.executionId.includes("change")) {
            safeOpenDetails('change', item.variables);
        } else if (item.executionId.includes("problem")) {
            safeOpenDetails('problem', item.variables);
        }
    });
};
</script>
<style scoped lang="scss">
:deep(.card) {
  padding: 10px;
  border: none;
}
</style>